﻿using Draco.OWF.Metadata;
using Draco.OWF.Metadata.Serialize;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace Draco.OWF.RT.Engine.Manager
{
    public class WorkflowManager
    {
        protected IDictionary<String, WorkflowModel> m_ProcessCollection = new Dictionary<String, WorkflowModel>();

        internal void LoadProcessFromDirectory(String dirURL)
        {
            if (!String.IsNullOrWhiteSpace(dirURL) && Directory.Exists(dirURL))
            {
                String[] files = Directory.GetFiles(dirURL, "*.owf");
                foreach (String file in files)
                {
                    LoadProcess(file);
                }

                String[] dirs = Directory.GetDirectories(dirURL);
                foreach (String dir in dirs)
                {
                    LoadProcessFromDirectory(dir);
                }
            }
        }
                
        public virtual WorkflowModel LoadProcess(String fileName)
        {
            if (!String.IsNullOrWhiteSpace(fileName) && File.Exists(fileName))
            {
                WorkflowModel workflow = XmlSerializer.DeserializeWorkflowProcessFromFile(fileName);
                this.LoadProcess(workflow);
                return workflow;
            }
            return null;
        }

        public virtual void LoadProcess(WorkflowModel process)
        {
            if (process != null && !m_ProcessCollection.ContainsKey(process.Id))
                m_ProcessCollection[process.Id] = process;
        }

        public virtual IList<WorkflowModel> LoadedProcesses
        {
            get
            {
                List<WorkflowModel> list = new List<WorkflowModel>();
                list.AddRange(m_ProcessCollection.Values);
                return list;
            }
        }

        public virtual WorkflowModel GetProcess(String processsId)
        {
            return m_ProcessCollection[processsId];

        }
    }
}
